﻿using System;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Security.Cryptography;         //用于创建加密哈希对象
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

namespace EidtTools
{
    public class EditBase
    {
        #region 保存上传的文件【基本文件操作】
        /// <summary>
        /// 保存上传的文件
        /// </summary>
        /// <param name="fileUpload">FileUpload上传控件</param>
        /// <param name="fileServerPath">要上传的文件在服务器中的物理路径</param>
        /// <param name="msg">返回信息</param>
        public static bool BasicSaveUploadFile(FileUpload fileUpload, string fileServerPath, ref string msg)
        {
            bool result;
            if (fileUpload.HasFile)
            {
                try
                {
                    fileUpload.SaveAs(fileServerPath);
                    result = true;
                    msg = "1";
                }
                catch (Exception ex)
                {
                    result = false;
                    msg = "上传时发生错误: " + ex.Message.ToString() + "。";
                }
            }
            else
            {
                result = false;
                msg = "上传时发生错误：没有找到该文件。";
            }

            return result;
        }
        #endregion

        #region 返回一个由当前时间所产生的数字字符串
        /// <summary>
        /// 返回一个由当前时间所产生的数字字符串
        /// </summary>
        public static string GetTimeNumber()
        {
            string thisTimeString;

            thisTimeString = DateTime.Now.ToString();
            thisTimeString = thisTimeString.Replace("-", "");
            thisTimeString = thisTimeString.Replace(":", "");
            thisTimeString = thisTimeString.Replace(" ", "");
            thisTimeString = thisTimeString.Replace("/", "");
            thisTimeString = thisTimeString.Replace("am", "");
            thisTimeString = thisTimeString.Replace("pm", "");
            thisTimeString = thisTimeString.Replace("AM", "");
            thisTimeString = thisTimeString.Replace("PM", "");

            return thisTimeString;
        }
        #endregion

        #region 返回一个区间内的随机整数
        /// <summary>
        /// 返回一个区间内的随机整数
        /// </summary>
        /// <param name="FromNum">区间起始数</param>
        /// <param name="ToNum">区间结束数</param>
        public static int GetRND(int fromNum, int toNum)
        {
            Random RND = new Random();
            return RND.Next(fromNum, toNum);
        }
        #endregion

        #region 输出JS代码

        /// <summary>
        /// 输出alert字符串，仅做提示
        /// </summary>
        /// <param name="alertStr">要显示的提示字符串</param>
        public static string RegisterJSAlert(string alertStr)
        {
            string theJSStr;
            theJSStr = "<script language=\"javascript\" type=\"text/javascript\">";
            theJSStr += "alert(\"" + alertStr.Replace("\n", "").Replace("\r", "") + "\");";
            theJSStr += "</" + "script>";
            return theJSStr;
        }

        /// <summary>
        /// 输出alert字符串，提示选择后选择跳转
        /// </summary>
        /// <param name="confirmStr">要显示的提示字符串</param>
        /// <param name="yesPath">如果浏览者点击“是”则跳转的路径</param>
        /// <param name="noPath">如果浏览者点击“否”则跳转的路径</param>
        public static string RegisterJSConfirmGOTO(string confirmStr, string yesPath, string noPath)
        {
            string theJSStr;
            theJSStr = "<script language=\"javascript\" type=\"text/javascript\">";
            theJSStr += "var add = confirm(\"" + confirmStr.Replace("\n", "").Replace("\r", "") + "\");";
            theJSStr += "if(add){location.assign(\"" + yesPath + "\");}";
            theJSStr += "else{location.assign(\"" + noPath + "\");}";
            theJSStr += "</" + "script>";
            return theJSStr;
        }

        /// <summary>
        /// 输出alert字符串，提示后直接跳转
        /// </summary>
        /// <param name="alertStr">要显示的提示字符串</param>
        /// <param name="gotoPath">要跳转的路径</param>
        public static string RegisterJSAlertGOTO(string alertStr, string gotoPath)
        {
            string theJSStr;
            theJSStr = "<script language=\"javascript\" type=\"text/javascript\">";
            theJSStr += "alert(\"" + alertStr.Replace("\n", "").Replace("\r", "") + "\");";
            theJSStr += "location.assign(\"" + gotoPath + "\");";
            theJSStr += "</" + "script>";
            return theJSStr;
        }

        /// <summary>
        /// 输出alert字符串，提示后直接跳转
        /// </summary>
        /// <param name="alertStr">要显示的提示字符串</param>
        /// <param name="gotoPath">要跳转的路径</param>
        /// <param name="isPrarent">是否使父窗口跳转</param>
        public static string RegisterJSAlertGOTO(string alertStr, string gotoPath, bool isPrarent)
        {
            string theJSStr;
            theJSStr = "<script language=\"javascript\" type=\"text/javascript\">";
            theJSStr += "alert(\"" + alertStr.Replace("\n", "").Replace("\r", "") + "\");";
            if (isPrarent)
            {
                theJSStr += "if(parent != null){";
                theJSStr += "parent.location.assign(\"" + gotoPath + "\");";
                theJSStr += "}else{";
                theJSStr += "location.assign(\"" + gotoPath + "\");";
                theJSStr += "}";
            }
            else
            {
                theJSStr += "location.assign(\"" + gotoPath + "\");";
            }
            theJSStr += "</" + "script>";
            return theJSStr;
        }

        /// <summary>
        /// 直接跳转
        /// </summary>
        /// <param name="gotoPath">要跳转的路径</param>
        /// <param name="isPrarent">是否使父窗口跳转</param>
        public static string RegisterJSGOTO(string gotoPath, bool isPrarent)
        {
            string theJSStr;
            theJSStr = "<script language=\"javascript\" type=\"text/javascript\">";
            if (isPrarent)
            {
                theJSStr += "if(parent != null){";
                theJSStr += "parent.location.assign(\"" + gotoPath + "\");";
                theJSStr += "}else{";
                theJSStr += "location.assign(\"" + gotoPath + "\");";
                theJSStr += "}";
            }
            else
            {
                theJSStr += "location.assign(\"" + gotoPath + "\");";
            }
            theJSStr += "</" + "script>";
            return theJSStr;
        }

        /// <summary>
        /// 输出alert字符串，提示后直接返回
        /// </summary>
        /// <param name="alertStr">要显示的提示字符串</param>
        public static string RegisterJSAlertGoBack(string alertStr)
        {
            //history.back
            string theJSStr;
            theJSStr = "<script language=\"javascript\" type=\"text/javascript\">";
            theJSStr += "alert(\"" + alertStr.Replace("\n", "").Replace("\r", "") + "\");";
            theJSStr += "history.back();";
            theJSStr += "</" + "script>";
            return theJSStr;
        }

        #endregion

        #region 保存缩略图
        ///  <summary> 
        ///  为传入的图像生成缩略图 
        ///  </summary> 
        ///  <param name="sourceImage">传入的图像</param> 
        /// <param name="SmallPicPath">缩小成缩略图的路径</param>
        ///  <param name="widthOfThumbnailImage">缩略图的宽度(像素)</param> 
        ///  <param name="heightOfThumbnailImage">缩略图的高度(像素)</param> 
        ///  <returns>System.Drawing.Image类型的缩略图</returns> 
        public static System.Drawing.Image GetThumbnailImage(System.Drawing.Image sourceImage, string SmallPicPath, int widthOfThumbnailImage, int heightOfThumbnailImage)
        {
            System.Drawing.Image imgThumb;
            int width = sourceImage.Width;
            int height = sourceImage.Height;

            imgThumb = new System.Drawing.Bitmap(widthOfThumbnailImage, heightOfThumbnailImage);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(imgThumb);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(sourceImage, new Rectangle(0, 0, widthOfThumbnailImage, heightOfThumbnailImage), 0, 0, width, height, GraphicsUnit.Pixel);
            imgThumb.Save(SmallPicPath);
            return imgThumb;
        }

        ///  <summary> 
        ///  为传入的图像生成缩略图 
        ///  </summary> 
        ///  <param name="sourceImage">传入的图像</param> 
        /// <param name="SmallPicPath">缩小成缩略图的路径</param>
        ///  <param name="widthOfThumbnailImage">缩略图的宽度(像素)</param> 
        ///  <returns>System.Drawing.Image类型的缩略图</returns> 
        public static System.Drawing.Image GetThumbnailImageWidth(System.Drawing.Image sourceImage, string SmallPicPath, int widthOfThumbnailImage)
        {
            System.Drawing.Image imgThumb;
            int width = sourceImage.Width;
            int height = sourceImage.Height;

            int heightOfThumbnailImage;
            float rate = (float)widthOfThumbnailImage / width;
            if (rate >= 1)
            {
                widthOfThumbnailImage = width;
                heightOfThumbnailImage = height;
            }
            else
            {
                heightOfThumbnailImage = (int)(rate * height);
            }

            imgThumb = new System.Drawing.Bitmap(widthOfThumbnailImage, heightOfThumbnailImage);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(imgThumb);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(sourceImage, new Rectangle(0, 0, widthOfThumbnailImage, heightOfThumbnailImage), 0, 0, width, height, GraphicsUnit.Pixel);
            imgThumb.Save(SmallPicPath);
            return imgThumb;
        }

        ///  <summary> 
        ///  为传入的图像生成缩略图 
        ///  </summary> 
        ///  <param name="sourceImage">传入的图像</param> 
        /// <param name="SmallPicPath">缩小成缩略图的路径</param>
        ///  <param name="heightOfThumbnailImage">缩略图的高度(像素)</param> 
        ///  <returns>System.Drawing.Image类型的缩略图</returns> 
        public static System.Drawing.Image GetThumbnailImageHeight(System.Drawing.Image sourceImage, string SmallPicPath, int heightOfThumbnailImage)
        {
            System.Drawing.Image imgThumb;
            int width = sourceImage.Width;
            int height = sourceImage.Height;

            int widthOfThumbnailImage;
            float rate = (float)heightOfThumbnailImage / height;
            if (rate >= 1)
            {
                widthOfThumbnailImage = width;
                heightOfThumbnailImage = height;
            }
            else
            {
                widthOfThumbnailImage = (int)(rate * width);
            }

            imgThumb = new System.Drawing.Bitmap(widthOfThumbnailImage, heightOfThumbnailImage);

            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(imgThumb);
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            g.DrawImage(sourceImage, new Rectangle(0, 0, widthOfThumbnailImage, heightOfThumbnailImage), 0, 0, width, height, GraphicsUnit.Pixel);
            imgThumb.Save(SmallPicPath);

            return imgThumb;
        }

        /// <SUMMARY>
        /// 图片缩放
        /// </SUMMARY>
        /// <PARAM name="sourceFile">图片源路径</PARAM>
        /// <PARAM name="destFile">缩放后图片输出路径</PARAM>
        /// <PARAM name="destHeight">缩放后图片高度</PARAM>
        /// <PARAM name="destWidth">缩放后图片宽度</PARAM>
        /// <RETURNS></RETURNS>
        public static System.Drawing.Image GetThumbnail(System.Drawing.Image imgSource, string destFile, int destHeight, int destWidth)
        {
            //System.Drawing.Image imgSource = System.Drawing.Image.FromFile(sourceFile);
            System.Drawing.Imaging.ImageFormat thisFormat = imgSource.RawFormat;
            int sW = 0, sH = 0;
            // 按比例缩放
            int sWidth = imgSource.Width;
            int sHeight = imgSource.Height;

            if (sHeight > destHeight || sWidth > destWidth)
            {
                if ((sWidth * destHeight) > (sHeight * destWidth))
                {
                    sW = destWidth;
                    sH = (destWidth * sHeight) / sWidth;
                }
                else
                {
                    sH = destHeight;
                    sW = (sWidth * destHeight) / sHeight;
                }
            }
            else
            {
                sW = sWidth;
                sH = sHeight;
            }

            Bitmap outBmp = new Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage(outBmp);
            g.Clear(Color.AliceBlue);

            // 设置画布的描绘质量
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(imgSource, new Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH), 0, 0, imgSource.Width, imgSource.Height, GraphicsUnit.Pixel);
            g.Dispose();

            // 以下代码为保存图片时，设置压缩质量
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;

            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];//设置JPEG编码
                    break;
                }
            }

            if (jpegICI != null)
            {
                outBmp.Save(destFile, jpegICI, encoderParams);
            }
            else
            {
                outBmp.Save(destFile, thisFormat);
            }

            outBmp.Dispose();

            return imgSource;
        }

        /// <summary>
        /// 保存缩略图。依赖项：ThumbnailCallback回调方法
        /// </summary>
        /// <param name="BigPicPath">原始大图片的路径</param>
        /// <param name="SmallPicPath">缩小成缩略图的路径</param>
        /// <param name="SmallPicWidth">缩略图的宽</param>
        public static void SaveSmallPicWidth(string BigPicPath, string SmallPicPath, int SmallPicWidth, ImageFormat saveFormat)
        {
            System.Drawing.Image imgBig = System.Drawing.Image.FromFile(BigPicPath);
            float SmallPicHeight;
            if (imgBig.Width >= SmallPicWidth)
            {
                SmallPicHeight = ((float)imgBig.Height) * ((float)SmallPicWidth / (float)imgBig.Width);
            }
            else
            {
                SmallPicWidth = imgBig.Width;
                SmallPicHeight = imgBig.Height;
            }
            System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            System.Drawing.Image imgSmall = imgBig.GetThumbnailImage(SmallPicWidth, (int)SmallPicHeight, myCallBack, IntPtr.Zero);
            imgSmall.Save(SmallPicPath, saveFormat);
        }
        /// <summary>
        /// 保存缩略图。依赖项：ThumbnailCallback回调方法
        /// </summary>
        /// <param name="BigPicPath">原始大图片的路径</param>
        /// <param name="SmallPicPath">缩小成缩略图的路径</param>
        /// <param name="SmallPicHeight">缩略图的高</param>
        public static void SaveSmallPicHeight(string BigPicPath, string SmallPicPath, int SmallPicHeight, ImageFormat saveFormat)
        {
            System.Drawing.Image imgBig = System.Drawing.Image.FromFile(BigPicPath);
            float SmallPicWidth;
            if (imgBig.Height >= SmallPicHeight)
            {
                SmallPicWidth = ((float)imgBig.Width) * ((float)SmallPicHeight / (float)imgBig.Height);
            }
            else
            {
                SmallPicWidth = imgBig.Width;
                SmallPicHeight = imgBig.Height;
            }
            System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            System.Drawing.Image imgSmall = imgBig.GetThumbnailImage((int)SmallPicWidth, SmallPicHeight, myCallBack, IntPtr.Zero);
            imgSmall.Save(SmallPicPath, saveFormat);
        }
        /// <summary>
        /// 保存缩略图。依赖项：ThumbnailCallback回调方法
        /// </summary>
        /// <param name="BigPicPath">原始大图片的路径</param>
        /// <param name="SmallPicPath">缩小成缩略图的路径</param>
        /// <param name="SmallPicWidth">缩略图的宽</param>
        /// <param name="SmallPicHeight">缩略图的高</param>
        public static void SaveSmallPic(string BigPicPath, string SmallPicPath, int SmallPicWidth, int SmallPicHeight, ImageFormat saveFormat)
        {
            System.Drawing.Image imgBig = System.Drawing.Image.FromFile(BigPicPath);
            System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            System.Drawing.Image imgSmall = imgBig.GetThumbnailImage(SmallPicWidth, SmallPicHeight, myCallBack, IntPtr.Zero);
            imgSmall.Save(SmallPicPath, saveFormat);

            imgBig.Dispose();
            //imgSmall.Dispose();
        }
        /// <summary>
        /// 保存缩略图。依赖项：ThumbnailCallback回调方法
        /// </summary>
        /// <param name="imgBig">原始大图片的对象</param>
        /// <param name="SmallPicPath">缩小成缩略图的路径</param>
        /// <param name="SmallPicWidth">缩略图的宽</param>
        public static System.Drawing.Image SaveSmallPicWidth(System.Drawing.Image imgBig, string SmallPicPath, int SmallPicWidth, ImageFormat saveFormat)
        {
            float SmallPicHeight;
            if (imgBig.Width >= SmallPicWidth)
            {
                SmallPicHeight = ((float)imgBig.Height) * ((float)SmallPicWidth / (float)imgBig.Width);
            }
            else
            {
                SmallPicWidth = imgBig.Width;
                SmallPicHeight = imgBig.Height;
            }
            System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            System.Drawing.Image imgSmall = imgBig.GetThumbnailImage(SmallPicWidth, (int)SmallPicHeight, myCallBack, IntPtr.Zero);
            imgSmall.Save(SmallPicPath, saveFormat);
            return imgSmall;
        }
        /// <summary>
        /// 保存缩略图。依赖项：ThumbnailCallback回调方法
        /// </summary>
        /// <param name="imgBig">原始大图片的对象</param>
        /// <param name="SmallPicPath">缩小成缩略图的路径</param>
        /// <param name="SmallPicHeight">缩略图的高</param>
        public static System.Drawing.Image SaveSmallPicHeight(System.Drawing.Image imgBig, string SmallPicPath, int SmallPicHeight, ImageFormat saveFormat)
        {
            float SmallPicWidth;
            if (imgBig.Height >= SmallPicHeight)
            {
                SmallPicWidth = ((float)imgBig.Width) * ((float)SmallPicHeight / (float)imgBig.Height);
            }
            else
            {
                SmallPicWidth = imgBig.Width;
                SmallPicHeight = imgBig.Height;
            }
            System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            System.Drawing.Image imgSmall = imgBig.GetThumbnailImage((int)SmallPicWidth, SmallPicHeight, myCallBack, IntPtr.Zero);
            imgSmall.Save(SmallPicPath, saveFormat);
            return imgSmall;
        }
        /// <summary>
        /// 保存缩略图。依赖项：ThumbnailCallback回调方法
        /// </summary>
        /// <param name="imgBig">原始大图片的对象</param>
        /// <param name="SmallPicPath">缩小成缩略图的路径</param>
        /// <param name="SmallPicWidth">缩略图的宽</param>
        /// <param name="SmallPicHeight">缩略图的高</param>
        public static System.Drawing.Image SaveSmallPic(System.Drawing.Image imgBig, string SmallPicPath, int SmallPicWidth, int SmallPicHeight, ImageFormat saveFormat)
        {
            System.Drawing.Image.GetThumbnailImageAbort myCallBack = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
            System.Drawing.Image imgSmall = imgBig.GetThumbnailImage(SmallPicWidth, SmallPicHeight, myCallBack, IntPtr.Zero);
            imgSmall.Save(SmallPicPath, saveFormat);
            return imgSmall;
        }
        /// <summary>
        /// 提供一个回调方法，用于确定 GetThumbnailImage 方法应在何时提前取消执行
        /// </summary>
        public static bool ThumbnailCallback()
        {
            return false;
        }
        #endregion

        #region 初始化URL参数
        public static string InitReValue(string requestName, string hidId)
        {
            string curID = string.Empty;
            HiddenField hidCurrentField = null;
            Page pg = (Page)HttpContext.Current.Handler;
            if (HttpContext.Current.Request.QueryString[requestName] != null)
            {
                curID = HttpContext.Current.Request.QueryString[requestName].ToString().Trim();
            }
            if (((HiddenField)pg.FindControl(hidId)) != null)
            {
                hidCurrentField = ((HiddenField)pg.FindControl(hidId));
            }

            if (curID != string.Empty)
            {
                if (hidCurrentField != null)
                {
                    hidCurrentField.Value = curID;
                }
                return curID;
            }
            else if (hidCurrentField != null)
            {
                return hidCurrentField.Value;
            }
            else
            {
                return string.Empty;
            }
        }
        public static string InitReValue(string requestName, HiddenField hidCurrentField)
        {
            string curID = string.Empty;
            if (HttpContext.Current.Request.QueryString[requestName] != null)
            {
                curID = HttpContext.Current.Request.QueryString[requestName].ToString().Trim();
            }

            if (curID != string.Empty)
            {
                if (hidCurrentField != null)
                {
                    hidCurrentField.Value = curID;
                }
                return curID;
            }
            else if (hidCurrentField != null)
            {
                return hidCurrentField.Value;
            }
            else
            {
                return string.Empty;
            }
        }
        #endregion
    }
}